#pragma once
#include <string>
#include <unordered_set>
#include <cstdio>

namespace wxd
{
    class Command
    {
    private:
        bool IsWhiteList(const std::string& message)
        {
            for(auto it = _while_list.begin();it != _while_list.end();it++)
            {
                if(*it == message)
                {
                    return true;
                }
            }
            return false;
        }

    public:
        Command()
        {
            // 设置白名单命令-for test
            _while_list.emplace("ls");
            _while_list.emplace("touch test.txt");
            _while_list.emplace("pwd");
            _while_list.emplace("who");
            _while_list.emplace("whoami");
        }
        std::string Execute(const std::string message)
        {
            if(!IsWhiteList(message))
            {
                return "Permission denied！";
            }
            FILE *fp = popen(message.c_str(), "r");
            if (fp == nullptr)
            {
                return message + "命令不存在";
            }
            else
            {
                // 从fp文件流中读取数据
                char read_buffer[1024];
                char *ret = fgets(read_buffer, sizeof(read_buffer) - 1, fp);
                if (ret == nullptr)
                {
                    return "执行成功";
                }
                return read_buffer;
            }
        }

    private:
        // 存放白名单命令
        std::unordered_set<std::string> _while_list;
    };

}